﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 库位服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class StorageLocationService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<StorageLocation> _storageLocationRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public StorageLocationService(SqlSugarRepository<StorageLocation> storageLocationRep, ISqlSugarClient sqlSugarClient)
    {
        _storageLocationRep = storageLocationRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询库位 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询库位")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<StorageLocationOutput>> Page(PageStorageLocationInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _storageLocationRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.StorageLocationEncode.Contains(input.Keyword) || u.StorageLocationName.Contains(input.Keyword) || u.StorageLocationPosition.Contains(input.Keyword) || u.ReservoirHead.Contains(input.Keyword) || u.Remark.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.StorageLocationEncode), u => u.StorageLocationEncode.Contains(input.StorageLocationEncode.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.StorageLocationName), u => u.StorageLocationName.Contains(input.StorageLocationName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.StorageLocationPosition), u => u.StorageLocationPosition.Contains(input.StorageLocationPosition.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ReservoirHead), u => u.ReservoirHead.Contains(input.ReservoirHead.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remark), u => u.Remark.Contains(input.Remark.Trim()))
            .WhereIF(input.ReservoirId != null, u => u.ReservoirId == input.ReservoirId)
            .WhereIF(input.StorageLocationArea != null, u => u.StorageLocationArea == input.StorageLocationArea)
            .LeftJoin<Reservoir>((u, reservoir) => u.ReservoirId == reservoir.Id)
            .Select((u, reservoir) => new StorageLocationOutput
            {
                Id = u.Id,
                StorageLocationEncode = u.StorageLocationEncode,
                StorageLocationName = u.StorageLocationName,
                ReservoirId = u.ReservoirId,
                ReservoirFkDisplayName = $"{reservoir.ReservoirName}",
                StorageLocationPosition = u.StorageLocationPosition,
                StorageLocationArea = u.StorageLocationArea,
                ReservoirHead = u.ReservoirHead,
                Remark = u.Remark,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取库位详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取库位详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<StorageLocation> Detail([FromQuery] QueryByIdStorageLocationInput input)
    {
        return await _storageLocationRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加库位 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加库位")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddStorageLocationInput input)
    {
        var entity = input.Adapt<StorageLocation>();
        return await _storageLocationRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新库位 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新库位")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateStorageLocationInput input)
    {
        var entity = input.Adapt<StorageLocation>();
        await _storageLocationRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除库位 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除库位")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteStorageLocationInput input)
    {
        var entity = await _storageLocationRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _storageLocationRep.FakeDeleteAsync(entity);   //假删除
        //await _storageLocationRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除库位 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除库位")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteStorageLocationInput> input)
    {
        var exp = Expressionable.Create<StorageLocation>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _storageLocationRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _storageLocationRep.FakeDeleteAsync(list);   //假删除
        //return await _storageLocationRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataStorageLocationInput input)
    {
        var reservoirIdData = await _storageLocationRep.Context.Queryable<Reservoir>()
            .InnerJoinIF<StorageLocation>(input.FromPage, (u, r) => u.Id == r.ReservoirId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.ReservoirName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "reservoirId", reservoirIdData },
        };
    }
    
    /// <summary>
    /// 导出库位记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出库位记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageStorageLocationInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportStorageLocationOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "库位导出记录");
    }
    
    /// <summary>
    /// 下载库位数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载库位数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportStorageLocationOutput>(), "库位导入模板", (_, info) =>
        {
            if (nameof(ExportStorageLocationOutput.ReservoirFkDisplayName) == info.Name) return _storageLocationRep.Context.Queryable<Reservoir>().Select(u => $"{u.ReservoirName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入库位记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入库位记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportStorageLocationInput, StorageLocation>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 所属库区
                    var reservoirIdLabelList = pageItems.Where(x => x.ReservoirFkDisplayName != null).Select(x => x.ReservoirFkDisplayName).Distinct().ToList();
                    if (reservoirIdLabelList.Any()) {
                        var reservoirIdLinkMap = _storageLocationRep.Context.Queryable<Reservoir>().Where(u => reservoirIdLabelList.Contains($"{u.ReservoirName}")).ToList().ToDictionary(u => $"{u.ReservoirName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.ReservoirId = reservoirIdLinkMap.GetValueOrDefault(e.ReservoirFkDisplayName ?? "");
                            if (e.ReservoirId == null) e.Error = "所属库区链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.ReservoirId == null){
                            x.Error = "所属库区不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.StorageLocationArea == null){
                            x.Error = "面积不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<StorageLocation>>();
                    
                    var storageable = _storageLocationRep.Context.Storageable(rows)
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.StorageLocationEncode), "库位编号不能为空")
                        .SplitError(it => it.Item.StorageLocationEncode?.Length > 32, "库位编号长度不能超过32个字符")
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.StorageLocationName), "库位名称不能为空")
                        .SplitError(it => it.Item.StorageLocationName?.Length > 32, "库位名称长度不能超过32个字符")
                        .SplitError(it => it.Item.ReservoirId == null, "所属库区不能为空")
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.StorageLocationPosition), "位置不能为空")
                        .SplitError(it => it.Item.StorageLocationPosition?.Length > 32, "位置长度不能超过32个字符")
                        .SplitError(it => it.Item.StorageLocationArea == null, "面积不能为空")
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.ReservoirHead), "负责人不能为空")
                        .SplitError(it => it.Item.ReservoirHead?.Length > 32, "负责人长度不能超过32个字符")
                        .SplitError(it => it.Item.Remark?.Length > 32, "备注长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
